package dao.hibernate;

import java.util.ArrayList;
import java.util.List;

import model.NguoiDung;
import dao.NguoiDungDAO;

public class NguoiDungDAOHibernate extends GenericHibernateDAO<NguoiDung, String> implements NguoiDungDAO{

	@SuppressWarnings("unchecked")
	@Override
	public NguoiDung checkLogin(String username, String password) {
		List<NguoiDung> list = getSession()
		.createQuery(
				"FROM NguoiDung AS nguoiDung WHERE nguoiDung.idNguoiDung = :username AND nguoiDung.matKhau = :password")
		.setString("username", username)
		.setString("password", password)
		.list();
		
		if (list != null && list.size() > 0)
			return list.get(0);
		else 
			return null;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public List<NguoiDung> findByIdNguoiDungLike(String idNguoiDung) {
		return getSession()
		.createQuery(
				"FROM NguoiDung AS nguoiDung WHERE nguoiDung.idNguoiDung LIKE :pname")
		.setString("pname", "%" + idNguoiDung + "%").list();
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public List<NguoiDung> findByTenNguoiDungLike(String tenNguoiDung) {
		return getSession()
		.createQuery(
				"FROM NguoiDung AS nguoiDung WHERE nguoiDung.hoTen LIKE :pname")
		.setString("pname", "%" + tenNguoiDung + "%").list();
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public List<NguoiDung> findByIdNhomNguoiDungLike(String idNhom) {
		return getSession()
		.createQuery(
				"FROM NguoiDung AS nguoiDung WHERE nguoiDung.nhomNguoiDung.idNhomNguoiDung LIKE :pname")
		.setString("pname", "%" + idNhom + "%").list();
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public List<NguoiDung> findByEmailNguoiDungLike(String email) {
		return getSession()
		.createQuery(
				"FROM NguoiDung AS nguoiDung WHERE nguoiDung.email LIKE :pname")
		.setString("pname", "%" + email + "%").list();
	}
	
	public List<NguoiDung> findByOneCondition(String criteria,
			String keyWord) {
		List<NguoiDung> result = new ArrayList<NguoiDung>();
		if (criteria.equals("idNguoiDung")) {
			result = findByIdNguoiDungLike(keyWord);
		} else if (criteria.equals("tenNguoiDung")){
			result = findByTenNguoiDungLike(keyWord);
		} else if (criteria.equals("idNhomNguoiDung")) {
			result = findByIdNhomNguoiDungLike(keyWord);
		} else if (criteria.equals("email")){
			result = findByEmailNguoiDungLike(keyWord);
		}
		return result;
	}

	@Override
	public NguoiDung findByEmail(String email) {
		NguoiDung result = (NguoiDung) getSession()
		.createQuery(
				"FROM NguoiDung AS nguoiDung WHERE nguoiDung.email = :email")
		.setString("email", email)
		.uniqueResult();
		
		return result;
	}

}
